package com.yang.mall.controller.admin;


import com.yang.mall.entity.OLResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(tags = "【PC】文件上传")
public class UploadAdminController {
    @Autowired
    ResourceLoader resourceLoader;

    @Value("${web.upload-path}")
    private String uploadPath;

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "文件上传")
    public OLResponse uploadFiles(HttpServletRequest req,
                                      @RequestParam(required = false) MultipartFile file
    ) {
        try {
            String path = this.remoteFilePath(file);
            return new OLResponse<>().success(path);
        } catch (Exception e) {
            return new OLResponse<>().fail(e.getMessage());
        }
    }

    private String remoteFilePath(MultipartFile file) {

        String filename = file.getOriginalFilename();

        DateFormat df = new SimpleDateFormat("yyyyMMdd");

        Calendar calendar = Calendar.getInstance();

        String time = df.format(calendar.getTime());

        String newFilePath = this.uploadPath +"/upload/" + time + "/";

        File checkFile = new File(newFilePath);
        if ((!checkFile.exists()) && (!checkFile.isDirectory())){
            checkFile.mkdirs();
        }
        String filePath = newFilePath + filename;

        byte[] bytes = new byte[0];
        try {
            bytes = file.getBytes();

            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));

            stream.write(bytes);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "https://www.yangranran.cn/yang/upload/" + time + "/" + filename;
    }



}
